import os
import shutil
from datetime import datetime


class FileBackupTool:
    """
    文件备份工具类
    功能：将源目录中的最新文件备份到目标目录，并记录日志
    """

    def __init__(self, source_dir, backup_dir, log_file='backup.log', log_dir='logs'):
        """
        初始化备份工具
        :param source_dir: 源目录路径
        :param backup_dir: 备份目录路径
        :param log_file: 日志文件路径
        """

        self.source_dir = source_dir
        self.backup_dir = backup_dir
        self.log_file = log_file
        # self.log.dir = log_dir
        # self.log.file = os.path.join(log_dir, log_file)

        # 确保目录存在
        os.makedirs(backup_dir, exist_ok=True)

    def backup_files(self):
        """
        执行备份操作，只备份最新的文件
        """
        backup_time = datetime.now()
        time_str = backup_time.strftime('%Y_%m_%d_%H%M')  # 格式化为2025_5_16_0932

        log_entry = f"\n=== 备份开始于 {backup_time.strftime('%Y-%m-%d %H:%M:%S')} ===\n"

        try:
            # 获取源目录中所有文件及其修改时间
            files = []
            for filename in os.listdir(self.source_dir):
                filepath = os.path.join(self.source_dir, filename)
                if os.path.isfile(filepath):
                    mtime = os.path.getmtime(filepath)
                    files.append((mtime, filename, filepath))

            if not files:
                log_entry += "源目录中没有文件可备份\n"
            else:
                # 找到最新的文件
                files.sort(reverse=True)  # 按修改时间降序排列
                latest_mtime, latest_filename, latest_filepath = files[0]

                # 创建以时间命名的备份文件夹
                backup_folder_name = f"{time_str}_backup"
                target_folder = os.path.join(self.backup_dir, backup_folder_name)
                os.makedirs(target_folder, exist_ok=True)

                # 设置目标路径
                target_path = os.path.join(target_folder, latest_filename)

                # 执行备份
                shutil.copy2(latest_filepath, target_path)
                log_entry += f"已备份最新文件: {latest_filename} 到文件夹 {backup_folder_name}/\n"

            log_entry += f"=== 备份完成 ===\n"
            self._write_log(log_entry)
            print("备份完成！")

        except Exception as e:
            error_msg = f"备份过程中出错: {str(e)}\n"
            self._write_log(error_msg)
            print(error_msg)

    def _write_log(self, message):
        """
        写入日志文件
        :param message: 要记录的日志信息
        """
        with open(self.log_file, 'a', encoding='utf-8') as f:
            f.write(message)


# 使用示例
if __name__ == "__main__":
    # 配置源目录和备份目录
    SOURCE_DIR = "C:/Users/Administrator/Downloads"  # 替换为你的源目录
    BACKUP_DIR = "D:/LvHua/数据库备份"  # 替换为你的备份目录

    # 创建备份工具实例并执行备份
    backup_tool = FileBackupTool(SOURCE_DIR, BACKUP_DIR)
    backup_tool.backup_files()
